<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div
      v-if="defaultSettings.showBackChange"
      class="absolute top-0 flex items-center justify-end px-5 h-20 w-full"
    >
      <el-switch
        v-model="isDark"
        inline-prompt
        active-icon=""
        inactive-icon=""
        active-color="var(--el-fill-color-dark)"
        inactive-color="var(--el-color-primary)"
        @change="handleThemeChange"
      />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- logo显示 -->
    <div
      class="absolute top-[7px] flex items-center justify-start px-10 h-20 w-full mt-[30px]"
    >
      <img
        src="../../assets/images/logo-icon.png"
        :class="window7 ? 'w-[100px]' : 'w-[200px]'"
        alt=""
      />
    </div>
    <!-- 登录表单 -->
    <el-card
      class="z-1 !border-none w-100 !bg-transparent !rounded-4% <sm:w-92"
      :shadow="window7 ? 'never' : 'always'"
    >
      <div class="text-center relative">
        <h2>{{ appTitle }}</h2>
        <h2 class="text-[18px] font-400">{{ appCompany }}</h2>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginData"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <div class="p-2">
            <svg-icon icon-class="user" />
          </div>
          <el-input
            ref="username"
            v-model="loginData.username"
            class="flex-1"
            size="large"
            :placeholder="$t('login.username')"
            name="username"
          />
        </el-form-item>

        <el-tooltip
          :disabled="isCapslock === false"
          content="Caps lock is On"
          placement="right"
        >
          <el-form-item prop="password">
            <span class="p-2">
              <svg-icon icon-class="password" />
            </span>
            <!-- <el-input
              v-model="loginData.password"
              class="flex-1"
              :placeholder="$t('login.password')"
              :type="passwordVisible === false ? 'password' : 'input'"
              auto-complete="new-password"
              size="large"
              name="password"
              @keyup="checkCapslock"
              @keyup.enter="handleLogin"
            /> -->
            <el-input
              v-model="loginData.password"
              class="flex-1"
              :placeholder="$t('login.password')"
              auto-complete="new-password"
              size="large"
              name="password"
              :class="passwordVisible === false ? 'no-autofill-pwd' : ''"
              @keyup="checkCapslock"
              @keyup.enter="handleLogin"
            />
            <span class="mr-2" @click="passwordVisible = !passwordVisible">
              <svg-icon
                :icon-class="passwordVisible === false ? 'eye' : 'eye-open'"
                class="cursor-pointer"
              />
            </span>
          </el-form-item>
        </el-tooltip>

        <!-- 验证码 -->
        <!-- <el-form-item prop="verifyCode">
          <span class="p-2">
            <svg-icon icon-class="verify-code" />
          </span>

          <el-input
            v-model="loginData.verifyCode"
            auto-complete="off"
            :placeholder="$t('login.verifyCode')"
            class="w-[60%]"
            @keyup.enter="handleLogin"
          />

          <div class="captcha">
            <el-image
              :src="captchaBase64"
              @click="getCaptcha"
              class="w-[120px] h-[48px] cursor-pointer"
            >
              <template #error>
                <div class="image-slot">
                  <i-ep-picture />
                </div>
              </template>
</el-image>
</div>
</el-form-item> -->

        <el-checkbox v-model="rememberPsw" class="mt-[-10px] mb-[20px]">
          记住密码
        </el-checkbox>

        <el-button
          :loading="loading"
          type="primary"
          class="w-full h-[40px] loginButton"
          @click.prevent="handleLogin"
          >{{ $t("login.login") }}
        </el-button>

        <!-- 账号密码提示 -->
        <!-- <div class="mt-10 text-sm">
          <span>{{ $t("login.username") }}: admin</span>
          <span class="ml-4"> {{ $t("login.password") }}: 123456</span>
        </div> -->
      </el-form>
    </el-card>

    <!-- ICP备案 -->
    <div class="absolute bottom-1 text-[10px] text-center">
      <p></p>
      <p></p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import router from "@/router";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { useSettingsStore } from "@/store/modules/settings";
import { useCookies } from "@vueuse/integrations/useCookies";
import { decrypt } from "@/utils/crypto";
import { getTimeState, isWindow7 } from "@/utils/index";

import { usePermissionStoreHook } from "@/store/modules/permission";
import { storeToRefs } from "pinia";

// 状态管理依赖
import { useUserStore } from "@/store/modules/user";
import { useAppStore } from "@/store/modules/app";

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import { getCaptchaApi } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import defaultSettings from "@/settings";

const window7 = ref(false);

const permissionStore = usePermissionStoreHook();

const appStore = useAppStore();
const settingsStore = useSettingsStore();
const userStore = useUserStore();
const route = useRoute();
const cookies = useCookies(["username", "password"]);

/**
 * 预留黑白模式切换功能
 */
const isDark = ref<boolean>(settingsStore.theme === "dark");

function handleThemeChange(isDark: boolean) {
  useToggle(isDark);
  settingsStore.changeSetting({
    key: "theme",
    value: isDark ? "dark" : "light",
  });
}

/**
 * 记住密码
 */
const rememberPsw = ref(false);

/**
 * 按钮loading
 */
const loading = ref(false);
/**
 * 是否大写锁定
 */
const isCapslock = ref(false);
/**
 * 密码是否可见
 */
const passwordVisible = ref(false);
/**
 * 验证码图片Base64字符串
 */
const captchaBase64 = ref();

const appTitle = ref(import.meta.env.VITE_APP_TITLE);
const appCompany = ref(import.meta.env.VITE_APP_COMPANY);

/**
 * 登录表单引用
 */
const loginFormRef = ref(ElForm);

const loginData = ref<LoginData>({
  username: "",
  password: "",
});

const { t } = useI18n();

const loginRules = computed(() => {
  const prefix = appStore.language === "en" ? "Please enter " : "请输入";
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: `${prefix}${t("login.username")}`,
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        validator: passwordValidator,
        message: `${prefix}${t("login.password")}`,
      },
    ],
    // verifyCode: [
    //   {
    //     required: true,
    //     trigger: "blur",
    //     message: `${prefix}${t("login.verifyCode")}`,
    //   },
    // ],
  };
});

/**
 * 密码校验器
 */
function passwordValidator(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error("The password can not be less than 6 digits"));
  } else {
    callback();
  }
}

/**
 * 检查输入大小写状态
 */
function checkCapslock(e: any) {
  const { key } = e;
  isCapslock.value = key && key.length === 1 && key >= "A" && key <= "Z";
}

/**
 * 获取验证码
 */
// function getCaptcha() {
//   getCaptchaApi().then(({ data }) => {
//     const { captchaImgBase64, verifyCodeKey } = data;
//     loginData.value.verifyCodeKey = verifyCodeKey;
//     captchaBase64.value = captchaImgBase64;
//   });
// }

/**
 * 登录
 */
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value, rememberPsw.value)
        .then(() => {
          // 路由跳转
          const query: LocationQuery = route.query;
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );
          ElNotification({
            title: getTimeState(),
            message: `欢迎登录 ${import.meta.env.VITE_APP_TITLE}`,
            type: "success",
            duration: 3000,
          });
          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
          // 验证失败，重新生成验证码
          // getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

onBeforeMount(async () => {
  window7.value = isWindow7();
  userStore.setIsWindow7(window7.value);
});
onMounted(async () => {
  // getCaptcha();
  await permissionStore.setRouteType("");
  // 主题初始化
  const theme = useSettingsStore().theme;
  useSettingsStore().changeSetting({ key: "theme", value: theme });
  if (theme == "dark") {
    document.documentElement.classList.add("dark");
  } else {
    document.documentElement.classList.remove("dark");
  }

  if (cookies.get("username")) {
    loginData.value.username = decrypt(cookies.get("username"));
    loginData.value.password = decrypt(cookies.get("password"));
    rememberPsw.value = true;
  } else {
    loginData.value.username = "";
    loginData.value.password = "";
  }
});
</script>

<style lang="scss" scoped>
.no-autofill-pwd {
  :deep(.el-input__inner) {
    -webkit-text-security: disc !important;
  }
}

.dark .login-container {
  background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
}

.login-container {
  @apply w-full h-full flex-center;

  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat center right;

  .loginButton {
    background-color: var(--menuBg);
    border-color: var(--menuBg);
  }

  .login-form {
    padding: 30px 10px;

    .captcha {
      position: absolute;
      top: 0;
      right: 0;

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: right;
        width: 100%;
        height: 100%;
        font-size: 18px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);

        svg {
          margin-right: 10px;
        }
      }
    }
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 5000s ease-in-out 0s;
      /* 通过延时渲染背景色变相去除背景颜色 */
    }
  }
}
</style>
